package com.ganwei.mybatisplus.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ganwei.mybatisplus.config.util.PicUtil;
import com.ganwei.mybatisplus.config.util.ResultVo;
import com.ganwei.mybatisplus.system.pojo.Product;
import com.ganwei.mybatisplus.system.service.IProductService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ganwei
 * @since 2020-10-08
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private IProductService iProductService;

    @GetMapping("/pageProduct")
    public ResultVo pageProducts(@Valid @NotNull(message = "pageNum不能为空") Integer pageNum ,
                                 @Valid @NotNull(message = "pageSize不能为空") Integer pageSize,
                                 String searchName){
        try {
            Page<Product> productList = iProductService.pageProduct(pageNum, pageSize,searchName);
            return ResultVo.success(200,"查询成功",productList);
        }catch (Exception e){
            return  ResultVo.error(500,"查询失败",null);
        }
    }

    @PostMapping("/updateState")
    public ResultVo updateState(@Valid @RequestBody Product product){
        int result = iProductService.updateProduct(product);
        return result==1 ?ResultVo.success(200,"修改成功",null):
                ResultVo.error(500,"修改失败",null);
    }

    @CrossOrigin(origins ="*",maxAge = 3600)
    @PostMapping("/uploading/img")
    public ResultVo uploading(@RequestParam(value = "filePic") MultipartFile filePic) throws IOException {
        Map map = PicUtil.singleFileUpload(filePic);
        String fileName =filePic.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        return ResultVo.success(200,"上传成功",map);
    }

    @PostMapping("/uploading/deFile")
    @CrossOrigin(origins ="*",maxAge = 3600)
    public ResultVo deFile(@RequestBody JSONObject str) throws IOException {
        Map maps = (Map) JSONObject.parse(String.valueOf(str));
        String s = PicUtil.deFile((String) maps.get("str"));
        return ResultVo.success(200,"删除成功",s);
    }
}